/*当要使用的插件很多时可以使用gulp-load-plugins插件来。
 用法：
gulp-load-plugins这个插件能自动帮你加载package.json文件里的gulp插件
gulp-load-plugins并不会一开始就加载所有package.json里的gulp插件，而是在我们需要用到某个插件的时候，才去加载那个插件。
var plugins = require('gulp-load-plugins')();
要使用gulp-rename和gulp-ruby-sass这两个插件的时候，就可以使用plugins.rename和plugins.rubySass来代替了,
也就是原始插件名去掉gulp-前缀，之后再转换为驼峰命名。*/
/*加载要用的插件*/
var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
//以下插件都可用plugins来表示
var sass = require('gulp-sass');
var browserSync = require('browser-sync');
var useref = require('gulp-useref');
var uglify = require('gulp-uglify');
var gulpif = require('gulp-if');
var minifyCss = require('gulp-clean-css');
var imagemin = require('gulp-imagemin');
var cache = require('gulp-cache');
var del = require('del');
var runSequence = require("run-sequence");


gulp.task('browserSync',function(){
browserSync({
server:{
baseDir:"app",
index:"test-gulp.html"
}
})
})

gulp.task('sass',function(){
  return gulp.src('app/scss/**/*.scss',{base:'app/scss'})
.pipe(plugins.sass())//用到插件gulp-load-plugins
.pipe(gulp.dest('app/css'))
.pipe(browserSync.reload({
stream: true
}))
});

var watcher = gulp.watch('app/scss/**/*.scss',['sass']);
gulp.task('watch',['sass','browserSync'],function(){
watcher.on('change',function(event) {
  console.log("File " + event.path + " was" + event.type +",running task...")
});
gulp.watch('app/*.html',browserSync.reload);
gulp.watch('app/js/**/*.js',browserSync.reload);
});

gulp.task('useref',function(){
return gulp.src('app/test-gulp.html')
    .pipe(useref())
    .pipe(gulpif('*.js',uglify()))
    .pipe(gulpif('*.css',minifyCss()))
    .pipe(gulp.dest('dist'))
});

gulp.task('jsmin',function(){
gulp.src('app/**/*.js')
.pipe(uglify())
.pipe(gulp.dest('dist/js'));
});

gulp.task('imagemin',function(){
  return gulp.src(["!app/images/{D,H}*.jpg","app/images/**/*.+(jpg|gif|png|svg)"])
      .pipe(cache(imagemin({interlaced:true})))
      .pipe(gulp.dest("dist/images"));
})

/* 需要删除包括图片的所有内容时 */
gulp.task('clean',function(callback){
  del("dist");
  return cache.clearAll(callback);
})

gulp.task("clean:dist",function(callback){
  del(["dist/**/*","!dist/images","!dist/images/**/*"],callback);
})

gulp.task("default",function (callback) {
runSequence(["watch","useref","imagemin","clean"],callback)

})